'use strict';

module.exports = (req, res, rfun)=>{
    let dv = {s:1,m:"error",u:""};
    if(req.POST && req.POST.jsoncs) req.POST = JSON.parse(req.POST.jsoncs);
    delete res.DATA;
    //console.log(req.POST);

    switch(req.GET.pathname){
        case "/Login/UserLogin":{ //用户登录
            if(req.POST.phoneCode != req.SESSION.sms){
                dv.m = "验证码错误";
                break;
            }
            delete req.SESSION.sms;
            var sql = "DECLARE @ret int = -1;EXEC @ret = [QPGameUserDB].[dbo].[YJ_GSP_GP_EfficacyAccounts] @strAccounts,@strPassword,@strClientIP,'webht',0,200000;SELECT @ret code";
            req.PUBFUN.DBM.executeSql(sql, function(rs){
                if(rs.UserID){
                    dv.u = "/Home/Index";
                    dv.m = "登录成功";
                    dv.s = 0;
                    req.SESSION.accounts = rs.Accounts[0];
                    req.SESSION.userid = rs.UserID[0];
                    req.SESSION.nickname = rs.NickName[0];
                    req.SESSION.gameid = rs.GameID[0];
                    req.SESSION.score = rs.GameGold[0];
                    req.SESSION.insurescore = rs.InsureGold[0];
                    req.SESSION.bankpwd = "";
                    for(let k in SESSION){
                        if(req.SESSION == SESSION[k]) continue;
                        if(SESSION[k].userid == req.SESSION.userid) delete SESSION[k];
                    }
                }else{
                    //dv.m += rs.code[rs.code.length-1];
                    dv.m = "账号或密码错误";
                }
                rfun(dv);
            },[
                { name: "strAccounts", type: req.PUBFUN.DBM.TYPES.VarChar, value: req.POST.userName, options:{length:64}},
                { name: "strPassword", type: req.PUBFUN.DBM.TYPES.Char, value: req.PUBFUN.MD5(req.POST.loginPwd) },
                { name: "strClientIP", type: req.PUBFUN.DBM.TYPES.VarChar, value: (req.headers["x-forwarded-for"] && req.headers["x-forwarded-for"].split(',')[0]) || req.socket.localAddress },
            ]);
            return;
        }case "/Login/LoginOut":{ //退出登录
            req.SESSION.userid = 0;
            res.setHeader("location","/Login/Index");
            res.statusCode = 302;
            res.end();
            rfun(false);
            return;
        }case "/Home/SearchNickNameByGameID":{ //根据gameid获取玩家信息
            //console.log(req.headers);
            req.PUBFUN.DBM.executeSql('SELECT UserID,GameID,NickName FROM [QPGameUserDB].[dbo].[AccountsBaseInfo] where GameID=@GameID', (row)=>{
                if(row.UserID){
                    dv.s = 0;
                    dv.m = row.NickName[0];
                }else{
                    dv.m = "没有找到该玩家！";
                }
                rfun(dv);
            }, [{ name: "GameID", type: req.PUBFUN.DBM.TYPES.Int, value: req.POST.gid }])
            return;
        }case "/Login/LoginSendSMS":{ //发送短信到指定手机号
            let mcode = (Math.random()*999999|0).toString();
            if(mcode.length < 6) mcode = '000000'.substr(0,6-mcode.length) + mcode;
            req.SESSION.sms = mcode;
            sendCode(req.POST.userName, mcode);
            dv.m = "发送成功";
            dv.s = 0;
            req.LOG.error(req.POST.userName, mcode);
            break;
        }case "/Home/DealerSaveScore":{ //存游戏币
            req.PUBFUN.DBM.executeSql(`DECLARE @cd int = 0, @SCC BigInt;
            IF(EXISTS(SELECT UserID FROM QPTreasureDB.dbo.GameScoreLocker where UserID=@UserID and (KindID > 0 OR ServerID > 0)))
            BEGIN
                SET @cd = 202
            END
            IF(@cd = 0 AND EXISTS(SELECT UserID FROM QPTreasureDB.dbo.GameScoreInfo where UserID=@UserID and Score-@SC >= 0)) 
            BEGIN
                SET @SCC = -@SC
                EXEC [QPTreasureDB].[dbo].[sp_Upd_UserGameGoldAndInsure] @UserID,@SCC,@SC,0,0,43,'';
            END
            ELSE
            BEGIN
                IF(@cd = 0) set @cd = 201;
            END
            SELECT @cd code,Score,InsureScore FROM QPTreasureDB.dbo.GameScoreInfo where UserID=@UserID`, (row)=>{
                console.log(row);
                if(row.code[0] == 0){
                    dv.m = "存款成功";
                    req.SESSION.score = row.Score[0];
                    req.SESSION.insurescore = row.InsureScore[0];
                    dv.u = "/Home/Index";
                    dv.s = 0;
                }else if(row.code[0] == 202){
                    dv.m = "游戏中不能操作";
                }else if(row.code[0] == 201){
                    dv.m = "游戏币不够";
                }
                rfun(dv);
            }, [
                { name: "UserID", type: req.PUBFUN.DBM.TYPES.Int, value: req.SESSION.userid },
                { name: "SC", type: req.PUBFUN.DBM.TYPES.BigInt, value: req.POST.score|0 }
            ]);
            return;
        }case "/Home/DealerTakeScore":{ //取游戏币
            req.PUBFUN.DBM.executeSql(`DECLARE @cd int = 0, @SCC BigInt;
            IF(NOT EXISTS(SELECT UserID FROM [QPGameUserDB].[dbo].[AccountsBaseInfo] where UserID=@UserID and InsurePass=@PW))
            BEGIN
                SET @cd = 203
            END
            IF(EXISTS(SELECT UserID FROM QPTreasureDB.dbo.GameScoreLocker where UserID=@UserID and (KindID > 0 OR ServerID > 0)))
            BEGIN
                SET @cd = 202
            END
            IF(@cd = 0 AND EXISTS(SELECT UserID FROM QPTreasureDB.dbo.GameScoreInfo where UserID=@UserID and InsureScore-@SC >= 0)) 
            BEGIN
                SET @SCC = -@SC
                EXEC [QPTreasureDB].[dbo].[sp_Upd_UserGameGoldAndInsure] @UserID,@SC,@SCC,0,0,42,'';
            END
            ELSE
            BEGIN
                IF(@cd = 0) set @cd = 201;
            END
            SELECT @cd code,Score,InsureScore FROM QPTreasureDB.dbo.GameScoreInfo where UserID=@UserID`, (row)=>{
                if(row.code[0] == 0){
                    dv.m = "取款成功";
                    req.SESSION.score = row.Score[0];
                    req.SESSION.insurescore = row.InsureScore[0];
                    dv.u = "/Home/Index";
                    dv.s = 0;
                }else if(row.code[0] == 203){
                    dv.m = "银行密码错误";
                }else if(row.code[0] == 202){
                    dv.m = "游戏中不能操作";
                }else if(row.code[0] == 201){
                    dv.m = "游戏币不够";
                }
                rfun(dv);
            }, [
                { name: "UserID", type: req.PUBFUN.DBM.TYPES.Int, value: req.SESSION.userid },
                { name: "SC", type: req.PUBFUN.DBM.TYPES.BigInt, value: req.POST.score },
                { name: "PW", type: req.PUBFUN.DBM.TYPES.VarChar, value: req.PUBFUN.MD5(req.POST.pwd) }
            ]);
            return;
        }case "/Home/DealerTransScore":{ //转账
            req.PUBFUN.DBM.executeSql(`DECLARE @Nullity int, @ErrorDescribe VARCHAR(256)
            EXEC QPGameUserDB.[dbo].[sp_chk_UserNullity]  @UserID, @Nullity  output,@ErrorDescribe output
            SELECT @Nullity Nullity`, (row2,err1)=>{
                if(row2.Nullity[0] != 0){
                    dv.m = "账号已冻结，无法操作";
                    rfun(dv);
                    return;
                }
                req.PUBFUN.DBM.executeSql("DECLARE @ret int;exec @ret = [QPTreasureDB].[dbo].[S_UserTransfer] @dwUserID,@dwGameID,@lTransferScore,@strPassword,'','';SELECT @ret code", (row,err)=>{
                    //console.log(row);
                    if(row.code[row.code.length - 1] == 0){
                        dv.m = "转账成功";
                        req.SESSION.insurescore -= req.POST.score;
                        req.SESSION.bankpwd = req.POST.pwd;
                        dv.s = 0;
                        req.PUBFUN.DBM.executeSql("SELECT UserID,GameID,NickName FROM [QPGameUserDB].[dbo].[AccountsBaseInfo] where GameID=@GameID", (rs)=>{
                            dv.reobj = {sNickName:req.SESSION.nickname,sGameID:req.SESSION.gameid,tNickName:rs.NickName[0],tGameID:rs.GameID[0],Score:req.POST.score,TranTime:new Date().toLocaleString()};
                            rfun(dv);
                            //赠送返利赢分
                            //if(Math.random()*100 < 60){
                            req.PUBFUN.RS(2).HGET("UC:" + rs.UserID[0], "cJF", function(err, rep){
                                let cJF = [-1,0,0,0,0];
                                if(rep) cJF = JSON.parse(rep);
                                if(cJF[0] != new Date().getDate()) cJF = [new Date().getDate(),0,0,0,0]
                                req.PUBFUN.DBM.executeSql("SELECT SUM(Score) jf FROM GameDB.dbo.GameScoreInfo WHERE UserID = " + rs.UserID[0], (rss)=>{
                                    let cwin = 0;
                                    if(rss.jf[0] < -75000000){
                                        if(cJF[1] < 1){
                                            cwin = (1000*Math.random()|0)*10000 + 20000000;
                                            cJF[1]++;
                                        }
                                    }else if(rss.jf[0] < -30000000){
                                        if(cJF[2] < 1){
                                            cwin = (500*Math.random()|0)*10000 + 10000000;
                                            cJF[2]++;
                                        }
                                    }else if(rss.jf[0] < -15000000){
                                        if(cJF[3] < 1){
                                            cwin = (300*Math.random()|0)*10000 + 5000000;
                                            cJF[3]++;                                            
                                        }

                                    }else if(rss.jf[0] < -1500000){
                                        if(cJF[4] < 1){
                                            cwin = (200*Math.random()|0)*10000 + 1000000;
                                            cJF[4]++;
                                        }
                                    }
                                    if(cwin > 0){
                                        req.PUBFUN.RS(2).SADD("CLIST", rs.UserID[0]);
                                        req.PUBFUN.RS(2).HMSET("UC:" + rs.UserID[0], "cwin", cwin, "cprop", 70, "cK", 0, "cS", 0, "cG", rs.GameID[0], "cN", rs.NickName[0], "cJF", JSON.stringify(cJF));
                                        req.PUBFUN.RS(2).PUBLISH("CHDBS", "{\"wMainCmdID\":307,\"wSubCmdID\":9,\"web\":[0,0," + rs.UserID[0] + "]}");
                                    }
                                })
                            })
                            //}
                        },[{ name: "GameID", type: req.PUBFUN.DBM.TYPES.Int, value: req.POST.gid }])
                        return;
                    }else if(row.code[row.code.length - 1] == 10){
                        dv.m = "银行金币不足";
                    }else if(row.code[row.code.length - 1] == 8){
                        dv.m = "银行密码不正确或者输入有误";
                    }else if(row.code[row.code.length - 1] == 4){
                        dv.m = "转账失败，不满最低金额";
                    }else if(row.code[row.code.length - 1] == 5){
                        dv.m = "用户不存在";
                    }else if(row.code[row.code.length - 1] == 11){
                        dv.m = "抱歉亲为了您的财产安全，同个ID一分钟内只能转账一次，请稍后再试";
                    }else{
                        dv.m += row.code[row.code.length - 1];
                    }
                    rfun(dv);
                },[
                    { name: "dwUserID", type: req.PUBFUN.DBM.TYPES.Int, value: req.SESSION.userid },
                    { name: "dwGameID", type: req.PUBFUN.DBM.TYPES.Int, value: req.POST.gid },
                    { name: "lTransferScore", type: req.PUBFUN.DBM.TYPES.BigInt, value: req.POST.score },
                    { name: "strPassword", type: req.PUBFUN.DBM.TYPES.VarChar, value: "webtran5e"/*req.PUBFUN.MD5(req.POST.pwd)*/ }
                ]);
            },[
                { name: "UserID", type: req.PUBFUN.DBM.TYPES.Int, value: req.SESSION.userid }
            ]);
            return;
        }case "/Record/DealerTransCancel":{ //转帐取消
            req.PUBFUN.DBM.executeSql(`DECLARE @sc BIGINT, @ret int = 2, @tuid INT;
            UPDATE [GameDB].[dbo].[RTransfer] SET [Status] = 4 WHERE SUserID=@dwUserID AND DATEDIFF(S,WriteTime,GETDATE()) < 120 AND Status = 1 AND Rid=@rid
            IF(@@ROWCOUNT = 1)
            BEGIN
                SELECT @sc=-Score,@tuid=TUserID FROM [GameDB].[dbo].[RTransfer] WHERE  Rid = @rid AND SUserID = @dwUserID
                exec @ret = QPTreasureDB.dbo.sp_Upd_UserGameGoldAndInsure @tuid,0,@sc,0,0,56,''
                if(@ret = 0)
                BEGIN
                    SET @sc = -@sc
                    exec @ret = QPTreasureDB.dbo.sp_Upd_UserGameGoldAndInsure @dwUserID,0,@sc,0,0,55,''
                    SET @ret = 0;
                END
                ELSE
                BEGIN
                    UPDATE [GameDB].[dbo].[RTransfer] SET [Status] = 1 WHERE SUserID=@dwUserID AND Status = 4 AND Rid=@rid
                END
            END
            SELECT @ret code, @sc sc`, function(row){
                if(row.code[0] == 2){
                    dv.m = "已经过期";
                }else if(row.code[0] == 1){
                    dv.m = "对方已经转走";
                }else{
                    dv.m = "撤回成功";
                    dv.s = 0;
                    req.SESSION.insurescore += Number(row.sc[0]);
                }
                dv.u = "/Record/TranRecord";
                rfun(dv);
            },[
                { name: "dwUserID", type: req.PUBFUN.DBM.TYPES.Int, value: req.SESSION.userid },
                { name: "rid", type: req.PUBFUN.DBM.TYPES.Int, value: req.POST.rid }
            ]);
            return;
        }case "/Home/GetTopEmailCount":{
            dv.s = 0;
            break;
        }case "/Record/GetTranRecordList":{ //转出记录
            req.POST.pageIndex = req.POST.pageIndex | 0;
            let wsql = "";
            if(req.POST.gameid > 0) wsql = " AND B.TUserID=(SELECT UserID FROM QPGameUserDB.dbo.AccountsBaseInfo A WITH(NOLOCK) WHERE GameID = "+(req.POST.gameid|0)+")";
            req.PUBFUN.MSPage("SELECT Rid,CASE WHEN ([Status] = 1 AND DATEDIFF(S,WriteTime,GETDATE())>120) OR VIP=5 THEN 5 ELSE [Status] END [Status],CONVERT(varchar(32),WriteTime,120) CollectDate,NickName,A.GameID,Score SwapScore,VIP FROM [QPGameUserDB].[dbo].[AccountsBaseInfo] A WITH(NOLOCK) inner join [GameDB].[dbo].[RTransferV] B WITH(NOLOCK) ON A.UserID=B.TUserID where B.SUserID=@UserID" + wsql + " AND WriteTime >= @btime AND WriteTime < DATEADD(DAY,1,@etime)", "ORDER BY CollectDate DESC", (rs)=>{
                dv = {"list":{"rows":rs[0],"total":rs[1][0].total},"s":0,"m":"加载成功","u":"","total":[{"SwapScore":Number(rs[1][0].SwapScore)}],"usertotal":[{"SwapScore":Number(rs[1][0].uScore)}]};
                dv.list = JSON.stringify(dv.list);
                dv.total = JSON.stringify(dv.total);
                dv.usertotal = JSON.stringify(dv.usertotal);
                //console.log(rs[1],res.DATA, dv);
                rfun(dv);
            },[
                { name: "UserID", type: req.PUBFUN.DBM.TYPES.Int, value: req.SESSION.userid },
                { name: "btime", type: req.PUBFUN.DBM.TYPES.DateTime2, value: req.POST.stime },
                { name: "etime", type: req.PUBFUN.DBM.TYPES.DateTime2, value: req.POST.etime }
            ], req.POST.pageIndex,20,",SUM(CASE WHEN [Status]<>4 THEN SwapScore ELSE 0 END) SwapScore,SUM(CASE WHEN [Status]<>4 AND VIP <> 5 THEN SwapScore ELSE 0 END) uScore");
            return;
        }case "/Record/GetTransInRecordList":{ //转入记录
            req.POST.pageIndex = req.POST.pageIndex | 0;
            let wsql = "";
            if(req.POST.gameid > 0) wsql = " AND B.SUserID=(SELECT UserID FROM QPGameUserDB.dbo.AccountsBaseInfo A WITH(NOLOCK) WHERE GameID = "+(req.POST.gameid|0)+")";
            req.PUBFUN.MSPage("SELECT CONVERT(varchar(32),WriteTime,120) CollectDate,NickName,A.GameID,Status,Score SwapScore,VIP FROM [QPGameUserDB].[dbo].[AccountsBaseInfo] A WITH(NOLOCK) inner join [GameDB].[dbo].[RTransferV] B WITH(NOLOCK) ON A.UserID=B.SUserID where B.TUserID=@UserID" + wsql + " AND WriteTime >= @btime AND WriteTime < DATEADD(DAY,1,@etime)", "ORDER BY CollectDate DESC", (rs)=>{
                dv = {"list":{"rows":rs[0],"total":rs[1][0].total},"s":0,"m":"加载成功","u":"","total":[{"SwapScore":Number(rs[1][0].SwapScore)}],"usertotal":[{"SwapScore":Number(rs[1][0].uScore)}]};
                dv.list = JSON.stringify(dv.list);
                dv.total = JSON.stringify(dv.total);
                dv.usertotal = JSON.stringify(dv.usertotal);
                rfun(dv);
            },[
                { name: "UserID", type: req.PUBFUN.DBM.TYPES.Int, value: req.SESSION.userid },
                { name: "btime", type: req.PUBFUN.DBM.TYPES.DateTime2, value: req.POST.stime },
                { name: "etime", type: req.PUBFUN.DBM.TYPES.DateTime2, value: req.POST.etime }
            ], req.POST.pageIndex,20,",SUM(CASE WHEN Status=1 THEN SwapScore ELSE 0 END) SwapScore,SUM(CASE WHEN VIP <> 5 AND Status=1 THEN SwapScore ELSE 0 END) uScore");
            return;
        }case "/Record/GetRebateRecordList":{ //返利记录
            req.POST.pageIndex = req.POST.pageIndex | 0;
            //req.PUBFUN.MSPage("SELECT CONVERT(varchar(32),WriteTime,120) InsertDate,CASE WHEN RecordType=51 THEN '单笔1.8%奖励' WHEN RecordType=50 THEN '日销奖励' WHEN RecordType=49 THEN '朋友圈奖励' ELSE '净销奖励' END TName,CASE WHEN addInsureScore>0 THEN addInsureScore ELSE CONVERT(numeric(18,2),addIntegral/100.0) END Score,CASE WHEN addInsureScore>0 THEN '金币' ELSE '红包' END TypeName FROM [GameDB].[dbo].[GameScoreInfoLog] WITH(NOLOCK) where RecordType IN(52,50,51,49) AND WriteTime >= @btime AND WriteTime < DATEADD(DAY,1,@etime) AND UserID=@UserID", "ORDER BY InsertDate DESC", (rs)=>{
            req.PUBFUN.MSPage(`SELECT RecordID,Status,CONVERT(varchar(32),RQ,120) InsertDate,CASE WHEN RebateTypeID=11 THEN '单笔1.8%奖励' WHEN RebateTypeID=8 THEN '净销奖励' ELSE '日销奖励' END TName,Score,'金币' TypeName FROM [QPServerInfoDB].[dbo].[RebateRecord] WITH(NOLOCK) where RQ >= @btime AND RQ < DATEADD(DAY,1,@etime) AND UserID=@UserID
            UNION ALL 
            SELECT RecordID,1 Status,CONVERT(varchar(32),RQ,120) InsertDate,'朋友圈奖励' TName,Score,'金币' TypeName FROM [QPServerInfoDB].[dbo].[RewardRecord] WITH(NOLOCK) where RQ >= @btime AND RQ < DATEADD(DAY,1,@etime) AND UserID=@UserID`, "ORDER BY InsertDate DESC", (rs)=>{
                //console.log(rs[1]);
                dv = {"list":{"rows":rs[0],"total":rs[1][0].total},"s":0,"m":"加载成功","u":"","total":[{"GrantScore":rs[1][0].tScore}]};
                dv.list = JSON.stringify(dv.list);
                dv.total = JSON.stringify(dv.total);
                rfun(dv);
            },[
                { name: "UserID", type: req.PUBFUN.DBM.TYPES.Int, value: req.SESSION.userid },
                { name: "btime", type: req.PUBFUN.DBM.TYPES.DateTime2, value: req.POST.stime },
                { name: "etime", type: req.PUBFUN.DBM.TYPES.DateTime2, value: req.POST.etime }
            ], req.POST.pageIndex,20,",SUM(Score) tScore");          
            return;
        }case "/Record/DealerGetRebate":{ //领取返利
            req.PUBFUN.DBM.executeSql(`DECLARE @RebateTypeID INT,@Score INT
            UPDATE [QPServerInfoDB].[dbo].[RebateRecord] SET Status=1,@RebateTypeID=RebateTypeID,@Score=Score WHERE UserID=@UserID AND RecordID=@RecordID AND Status = 0
            IF(@@ROWCOUNT = 1)
            BEGIN
                IF(@RebateTypeID = 11)
                BEGIN
                    exec QPTreasureDB.dbo.sp_Upd_UserGameGoldAndInsure @UserID,0,@Score,0,0,51,''
                END
                ELSE IF(@RebateTypeID = 29)
                BEGIN
                    exec QPTreasureDB.dbo.sp_Upd_UserGameGoldAndInsure @UserID,0,@Score,0,0,52,''
                END
                ELSE
                BEGIN
                    exec QPTreasureDB.dbo.sp_Upd_UserGameGoldAndInsure @UserID,0,@Score,0,0,50,''
                END
                SELECT UserID,Score,InsureScore FROM QPTreasureDB.dbo.GameScoreInfo where UserID=@UserID
            END`, (rs)=>{
                if(rs.UserID){
                    req.SESSION.score = rs.Score[0];
                    req.SESSION.insurescore = rs.InsureScore[0];
                }
                dv.s = 0;
                dv.m = "领取成功";
                dv.u = "/Record/RebateRecord";
                rfun(dv);
            },[
                { name: "UserID", type: req.PUBFUN.DBM.TYPES.Int, value: req.SESSION.userid },
                { name: "RecordID", type: req.PUBFUN.DBM.TYPES.Int, value: req.POST.rid }
            ]);
            return;
        }case "/Total/GetTotalDataList":{ //日统计 周统计 月统计
            let sql = `SELECT CONVERT(varchar(10),WriteTime,120) InsertDate,SUM(CASE WHEN SUserID=@UserID THEN Score ELSE 0 END) TransTotal,SUM(CASE WHEN TUserID=@UserID THEN Score ELSE 0 END) ReceiveTotal,ISNULL(RebateTotal,0) RebateTotal 
            FROM [GameDB].[dbo].[RTransferV] A WITH(NOLOCK)
            INNER JOIN QPGameUserDB.dbo.AccountsBaseInfo C WITH(NOLOCK) ON A.SUserID = C.UserID
            INNER JOIN QPGameUserDB.dbo.AccountsBaseInfo D WITH(NOLOCK) ON A.TUserID = D.UserID
            LEFT JOIN (SELECT CONVERT(varchar(10),RQ,120) InsertDate,SUM(Score) RebateTotal FROM [QPServerInfoDB].[dbo].[RebateRecord] WITH(NOLOCK) 
                WHERE RQ >= @btime AND RQ < DATEADD(DAY,2,@etime) AND UserID=@UserID GROUP BY CONVERT(varchar(10),RQ,120)) B ON DATEDIFF(DAY,A.WriteTime,B.InsertDate) = 1
            WHERE ((SUserID=@UserID AND D.VIP <> 5) OR (TUserID=@UserID  AND C.VIP <> 5)) AND Status=1 AND WriteTime >= @btime AND WriteTime < DATEADD(DAY,1,@etime) 
            GROUP BY CONVERT(varchar(10),WriteTime,120),B.RebateTotal ORDER BY CONVERT(varchar(10),WriteTime,120) DESC`;
            if(req.POST.type == "week"){
                //sql = `SELECT CONVERT(varchar(10),MIN(WriteTime),120) InsertDate,DATEPART(WEEK,WriteTime) WeekID,SUM(CASE WHEN SUserID=@UserID THEN Score ELSE 0 END) TransTotal,SUM(CASE WHEN TUserID=@UserID THEN Score ELSE 0 END) ReceiveTotal,0 RebateTotal FROM [GameDB].[dbo].[RTransferV] WITH(NOLOCK) WHERE (SUserID=@UserID OR TUserID=@UserID) AND Status=1 AND WriteTime >= @btime AND WriteTime < DATEADD(DAY,1,@etime) GROUP BY DATEPART(WEEK,WriteTime) ORDER BY DATEPART(WEEK,WriteTime) DESC`;
                sql = `SELECT CONVERT(varchar(10),MIN(WriteTime),120) InsertDate,DATEPART(WEEK,WriteTime) WeekID,SUM(CASE WHEN SUserID=@UserID THEN Score ELSE 0 END) TransTotal,SUM(CASE WHEN TUserID=@UserID THEN Score ELSE 0 END) ReceiveTotal,ISNULL(RebateTotal,0) RebateTotal  
                FROM [GameDB].[dbo].[RTransferV] A WITH(NOLOCK)
                INNER JOIN QPGameUserDB.dbo.AccountsBaseInfo C WITH(NOLOCK) ON A.SUserID = C.UserID
                INNER JOIN QPGameUserDB.dbo.AccountsBaseInfo D WITH(NOLOCK) ON A.TUserID = D.UserID
                INNER JOIN (SELECT DATEPART(WEEK,DATEADD(DAY,1,RQ)) InsertDate,SUM(Score) RebateTotal FROM [QPServerInfoDB].[dbo].[RebateRecord] WITH(NOLOCK) 
                    WHERE RQ >= @btime AND RQ < DATEADD(DAY,2,@etime) AND UserID=@UserID GROUP BY DATEPART(WEEK,DATEADD(DAY,1,RQ))) B ON B.InsertDate = DATEPART(WEEK,WriteTime)
                WHERE ((SUserID=@UserID AND D.VIP <> 5) OR (TUserID=@UserID  AND C.VIP <> 5)) AND Status=1 AND WriteTime >= @btime AND WriteTime < DATEADD(DAY,1,@etime) 
                GROUP BY DATEPART(WEEK,WriteTime),B.RebateTotal ORDER BY DATEPART(WEEK,WriteTime) DESC`;
            }else if(req.POST.type == "month"){
                req.POST.stime += "-01";
                req.POST.etime += "-01";
                sql = `SELECT CONVERT(varchar(7),WriteTime,120) InsertDate,SUM(CASE WHEN SUserID=@UserID THEN Score ELSE 0 END) TransTotal,SUM(CASE WHEN TUserID=@UserID THEN Score ELSE 0 END) ReceiveTotal,ISNULL(RebateTotal,0) RebateTotal 
                FROM [GameDB].[dbo].[RTransferV] A WITH(NOLOCK)
                INNER JOIN QPGameUserDB.dbo.AccountsBaseInfo C WITH(NOLOCK) ON A.SUserID = C.UserID
                INNER JOIN QPGameUserDB.dbo.AccountsBaseInfo D WITH(NOLOCK) ON A.TUserID = D.UserID
                INNER JOIN (SELECT CONVERT(varchar(7),DATEADD(DAY,-1,RQ),120) InsertDate,SUM(Score) RebateTotal FROM [QPServerInfoDB].[dbo].[RebateRecord] WITH(NOLOCK) 
                    WHERE RQ >= @btime AND RQ < DATEADD(MM,1,@etime) AND UserID=@UserID GROUP BY CONVERT(varchar(7),DATEADD(DAY,-1,RQ),120)) B ON B.InsertDate = CONVERT(varchar(7),WriteTime,120)
                WHERE ((SUserID=@UserID AND D.VIP <> 5) OR (TUserID=@UserID  AND C.VIP <> 5)) AND Status=1 AND WriteTime >= @btime AND WriteTime < DATEADD(MM,1,@etime) 
                GROUP BY CONVERT(varchar(7),WriteTime,120),B.RebateTotal ORDER BY CONVERT(varchar(7),WriteTime,120) DESC`;
            }
            req.PUBFUN.DBM.executeSql(sql, (row)=>{
                dv = {"list":{"rows":row,"total":row.length},"s":0,"m":"加载成功","u":"","total":[{"TransTotal":0,"ReceiveTotal":0,"RebateTotal":0}]};
                dv.list = JSON.stringify(dv.list);
                for(let v of row){
                    dv.total[0].TransTotal += Number(v.TransTotal);
                    dv.total[0].ReceiveTotal += Number(v.ReceiveTotal);
                    dv.total[0].RebateTotal += Number(v.RebateTotal);
                }
                dv.total = JSON.stringify(dv.total);
                rfun(dv);
            },[
                { name: "UserID", type: req.PUBFUN.DBM.TYPES.Int, value: req.SESSION.userid },
                { name: "btime", type: req.PUBFUN.DBM.TYPES.DateTime2, value: req.POST.stime },
                { name: "etime", type: req.PUBFUN.DBM.TYPES.DateTime2, value: req.POST.etime }
            ],true)
            return;
        }case "/Total/GetCard":{ //查询实卡
            req.PUBFUN.DBM.executeSql(`SELECT  A.UserID, B.GameID, B.Accounts, C.SerialID, A.UserID, CONVERT(VARCHAR(32),A.WriteTime,120) ApplyDate, C.Gold
            FROM GameDB.dbo.GameScoreInfoLog A WITH (NOLOCK) 
            INNER JOIN QPGameUserDB.dbo.AccountsBaseInfo AS B WITH (NOLOCK) ON A.UserID = B.UserID AND A.RecordType = 9 
            INNER JOIN QPTreasureDB.dbo.LivcardAssociator C WITH (NOLOCK) ON A.ServerID = C.CardID
            WHERE C.SerialID = @sid`, (rs)=>{
                dv = {"list":{"rows":rs,"total":rs.length},"s":0,"m":"加载成功","u":"","total":[{"TransTotal":0,"ReceiveTotal":0,"RebateTotal":0}]};
                dv.list = JSON.stringify(dv.list);
                rfun(dv);
            },[{ name: "sid", type: req.PUBFUN.DBM.TYPES.VarChar, value: req.POST.card }], true);
            return;
        }
    }
    rfun(dv);
}

//发送手机验证码 网易易盾
function sendCode(mob, code){
    const https = require("https"), game = require("../../config/game"), fun = require("../pubfun");
    let op = {host:"sms.dun.163yun.com",port:443,path:"/v2/sendsms","method": "POST",
        headers:{
        "Content-Type":"application/x-www-form-urlencoded;charset=utf-8",
        "Content-Length":0
    }};
    let pd = {
        "businessId":game.sms.businessId,
        "mobile":mob,
        //"needUp":"true",
        "nonce":fun.MD5(Date.now()+"hong"),
        "params":"code="+code,
        "secretId":game.sms.secretId,
        "templateId":game.sms.templateId,
        "timestamp":Date.now().toString(),
        "version":"v2",
    }, pdstr = "", mdstr = "";
    for(let k in pd){
        //pdstr += k + "=" + (k=="params"?encodeURIComponent(pd[k]):pd[k]) + "&";
        pdstr += k + "=" + pd[k] + "&";
        mdstr += k + pd[k];
    }
    pdstr += "signature=" + fun.MD5(mdstr + game.sms.SECRETKEY); //console.log(pdstr, mdstr);
    op.headers["Content-Length"] = pdstr.length;
    https.request(op, (res)=>{
        let cd = Buffer.allocUnsafe(0);
        res.once("data", (chunk)=>{
            cd = Buffer.concat([cd, chunk], cd.length + chunk.length);
        });
        res.once("end", ()=>{
            LOG.info(mob, cd.toString());
        });
    }).end(pdstr);
}